package com.ajview.core.security.service;

import com.ajview.common.core.domain.bo.LoginUser;
import com.ajview.common.core.domain.eneity.SysUser;
import com.ajview.common.core.enums.UserStatus;
import com.ajview.common.core.exception.auth.AuthGlobalException;
import com.ajview.core.config.model.SecurityModel;
import com.ajview.core.web.service.SysPermissionService;
import com.ajview.system.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * @author ZhangJunJie
 * @Date 2022-04-27
 * <p>
 * 概要：用户验证处理
 */
@Service
@Slf4j
public class UserDetilServiceImpl implements UserDetailsService, UserDetailsPasswordService {

    @Resource
    private SysUserService sysUserServiceImpl;
    @Resource
    private SecurityModel securityModel;
    @Resource
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws AuthenticationException {
        // 根据登录名查询数据库
        SysUser sysUser = sysUserServiceImpl.getOne(new QueryWrapper<SysUser>().eq("login_name", username));
        if (ObjectUtils.isEmpty(sysUser)) {
            log.info("登录用户：{} 不存在.", username);
            throw new AuthGlobalException("登录用户[" + username + "]不存在");
        } else if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            log.info("登录用户：{} 已被停用于时间:{}.", username, sysUser.getUpdateTime());
            throw new AuthGlobalException("登录用户：[" + username + "] 已被停用");
        }
        return createUserDetails(sysUser);
    }

    private UserDetails createUserDetails(SysUser sysUser) {
        // 通过认证后将该用户的基本信息和权限信息封装到自定义的UserDetails中
        return new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, sysPermissionService.getMenuPermission(sysUser));
    }

    /**
     * 密码策略字段更新
     *
     * @param user
     * @param newPassword
     * @return
     */
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        log.info("登录用户：{} 密码策略自动更新", user.getUsername());
        LoginUser loginUser = (LoginUser) user;
        SysUser sysUser = loginUser.getSysUser();
        sysUser.setUpdateTime(null);
        sysUser.setPassword(newPassword);
        boolean isUpdateById = sysUserServiceImpl.updateById(sysUser);
        if (isUpdateById) {
            return createUserDetails(sysUser);
        }
        return null;
    }
}
